<template>
  <!--输入框-->
  <div style="height: 100%">
  <div class="input">
    <el-row>
    <el-input v-model="companyName"
              placeholder="请输入公司名称"
              style="width:200px"
              clearable
              size="large"
    />
    <el-button type="info" size="large" @click="searchCompany">搜索</el-button>
    <el-button type="info" size="large"  @click="dialogVisible = true;isRevise=false">创建公司</el-button>
    </el-row>
  </div>
<!--创建公司框-->
    <el-dialog
        v-model="dialogVisible"
        :title="isRevise===true?'修改公司信息':'创建公司'"
        width="500"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :show-close="false"
    >
      <el-form :model="form" label-width="auto" style="max-width: 600px" :rules="companyRules" ref="companyForm">
        <el-form-item label="公司全称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="公司税号" prop="taxNo">
          <el-input v-model="form.taxNo"  :disabled="isRevise===true"/>
        </el-form-item>
        <el-form-item label="注册时间">
          <el-col :span="11">
            <el-date-picker
                v-model="form.registerDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.status"></el-switch>
        </el-form-item>
        <el-form-item label="法人代表">
          <el-input v-model="form.legalName" />
        </el-form-item>
        <el-form-item label="公司所在地">
          <el-input v-model="form.addr" type="textarea" />
        </el-form-item>
        <el-form-item style="margin-left: 30%">
          <el-button type="primary" @click="createCompany">{{isRevise===true?'修改':'创建'}}</el-button>
          <el-button @click="cancelCreate">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


  <!--公司列表-->
  <div >
    <el-table
        :data="companysDetail"
        border
        style="width: 100%;">
      <el-table-column
          prop="id"
          label="公司id"
          width="80"
          align="center">
      </el-table-column>
      <el-table-column
          prop="name"
          label="公司全称"
          width="120"
          align="center">
      </el-table-column>
      <el-table-column
          prop="taxNo"
          label="税号"
          width="200"
          align="center">
      </el-table-column>
      <el-table-column
          prop="registerDate"
          label="注册时间"
          width="200"
          align="center">
      </el-table-column>
      <el-table-column
          prop="legalName"
          label="法人代表"
          width="200"
          align="center">
      </el-table-column>
      <el-table-column
          prop="addr"
          label="公司所在地"
          width="200"
          align="center">
      </el-table-column>
      <el-table-column
          prop="status"
          label="状态"
          width="100"
          align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status===1?'success':'danger'" disable-transitions>{{scope.row.status===1?'正常':'已禁用'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" >
        <template #default="scope">
          <el-button
              size="small"
              type="primary"
              @click="reviseCompany(scope.row)"
              >修改
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="deleteCompany(scope.row)"
              :disabled="scope.row.status===2"
              >禁用
            {{}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!--分页-->
  <Pagination :currentPage="1" :pageSize="20" :total="companysDetail.length"
              :handleSizeChange="5" :handleCurrentChange="5"></Pagination>

  </div>
</template>

<script>
import Pagination from '@/components/Pagination.vue'
import { ElMessage } from 'element-plus'
import API from "@/api/manage"

export default {
  data(){
    var validatortaxNumber=(rule,value,callback)=>{
      if(this.verifyID(value)){
        callback()
      }
      else{
            callback(new Error('税号格式错误'))
          }
        }
    return{
      companyName:'',
      //创建or修改变量
      isRevise:false,
      companysDetail:[],
      dialogVisible:false,
      form:{
        name:'',
        taxNo:'',
        registerDate:'',
        legalName:'',
        addr:'',
        status:true
      },
      companyRules:{
        name:[
          {required:true,message:'请输入公司全称',trigger:'blur'}
        ],
        taxNo:[
          {required:true,message:'请输入公司税号',trigger:'blur'},
          {validator:validatortaxNumber,trigger: "blur"}
        ]
      }
    }
  },
  methods:{
    // 将字符转换成对应的数值
    convert(ch) {
  var tab = "0123456789ABCDEFGHJKLMNPQRTUWXY";
  for (var i = 0; i < 31; ++i) {
    if (tab[i] === ch) {
      return i;
    }
  }
  return -1;
},

// 税号校验函数，正确则返回 true，否则返回 false
verifyID(id) {
  var weight = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28, 1];
  var sum = 0;
  if (id.length !== 18) {
    return false;
  }
  for (var i = 0; i < 18; i++) {
    var t = this.convert(id[i]);
    if (t < 0) {
      return false;
    }
    sum += t * weight[i];
  }
  return sum % 31 === 0;
},



// 搜索
    searchCompany(){
      let token=localStorage.getItem('token')
      API.queryCompany({
        name:this.companyName.trim()
      },token).then(res=>{
        if(res.data.success===true){
          this.companysDetail=res.data.content.records
        }
      }).catch(err=>{
        console.log(err)
      })
    },
    // 修改公司
    reviseCompany(item){
      this.isRevise=true
      let token=localStorage.getItem('token')
      this.dialogVisible=true
      localStorage.setItem('reviseCompanyId',item.id)
       // 公司信息回显
       API.queryCompany({
         name:item.name
       },token).then(res=>{
         this.form=res.data.content.records[0]
         let dateString=this.form.registerDate.toString()
         const year = parseInt(dateString.substring(0, 4), 10);
         const month = parseInt(dateString.substring(4, 6), 10) - 1; // 月份索引从0开始，需要减1
         const day = parseInt(dateString.substring(6, 8), 10);
         const date = new Date(year, month, day);
         this.form.registerDate=date.toString()
       }).catch(err=>{
         console.log(err)
       })
    },

    //禁用公司
    deleteCompany(item){
      let token=localStorage.getItem('token')
      API.deleteCompany({
        id:item.id
      },token).then(res=>{
        if(res.data.success===true){
          this.listCompany()
        }
      }).catch(err=>{
        console.log(err)
      })
    },

    // 创建or修改公司
    createCompany(){
      this.$refs["companyForm"].validate(valid=>{
        if(valid){
          let token=localStorage.getItem('token')
          let formattedDate;
          if(this.form.registerDate===''){
            formattedDate='';
          }
          else{
            const date=new Date(this.form.registerDate)
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 使用 padStart 补齐两位数
            const day = date.getDate().toString().padStart(2, '0');
            formattedDate = `${year}${month}${day}`;
          }
          let param={
            name:this.form.name,
            registerDate:formattedDate, //格式化后的
            legalName:this.form.legalName,
            taxNo:this.form.taxNo,
            addr:this.form.addr,
            status: this.form.status===true?1:2
          }
          //创建公司
          if(this.isRevise===false){
              API.createCompany(param,token).then(res=>{
                if(res.data.success===true){
                  ElMessage.success('公司创建成功！')
                  this.form={
                    name:'',
                    taxNo:'',
                    registerDate:'',
                    legalName:'',
                    addr:'',
                    status:true
                  }
                  this.listCompany()
                  this.dialogVisible=false
                }
              }).catch(err=>{
                console.log(err)
              })
          }
          else{
            param.id=localStorage.getItem('reviseCompanyId')
            API.updateCompany(param,token).then(res=>{
              if(res.data.success===true){
                this.dialogVisible=false
                this.form={
                  name:'',
                  taxNo:'',
                  registerDate:'',
                  legalName:'',
                  addr:'',
                  status:true
                }
                this.listCompany()
              }
            }).catch(err=>{
              this.$message.error(err.response.data.message)
            })
          }
        }
      })
    },
    cancelCreate(){
      this.dialogVisible=false;
      this.form={
            name:'',
            taxNo:'',
            registerDate:'',
            legalName:'',
            addr:'',
            status:true
      }
    },
    listCompany(){
      let token=localStorage.getItem('token')
      API.queryCompany({},token).then(res=>{
        this.companysDetail=res.data.content.records
      }).catch(err=>{
        console.log(err)
      })
    }
  },
  mounted() {
    this.listCompany()
  },

}






</script>

<style scoped>

</style>
